# -*- coding:utf-8 -*-
import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver import ActionChains

from appUtils import WaitSecond, browser_changeTopWindow, browser_doWait, waitInfiniti, getWebDriver

LoginName = "18133623141"
LoginPd = "Hrg123456"


def loadData(webProxyDriver):
    (browser, _, _) = webProxyDriver
    result = [];
    # 登录
    browser.get(
        "https://account.xiaomi.com/pass/serviceLogin?callback=https%3A%2F%2Fdev.mi.com%2Fsts%3Fsign%3DgP3Zl7gQ%252FunwzQ%252FxswtsmpDIKjA%253D%26followup%3Dhttps%253A%252F%252Fdev.mi.com%252Fmyitems%252F0%252F0%253FuserId%253D1305010377&sid=mideveloper&_locale=zh_CN")
    browser_doWait(browser)
    browser.find_element_by_id("username").send_keys(LoginName)
    browser.find_element_by_id("pwd").send_keys(LoginPd)
    browser.find_element_by_id("login-button").click()
    browser_doWait(browser)
    # 跳到下载量页面
    browser.get("https://dev.mi.com/datacenter/appview/2882303761517796064/0?userId=1305010377")
    browser_doWait(browser)
    # 解析数据
    browser.maximize_window()
    svg = browser.find_element_by_tag_name("svg")
    series = svg.find_element_by_css_selector("g[class='highcharts-series-group']")
    width = series.size["width"]
    height = series.size["height"]
    count = 31
    itemWidth = width / count
    itemHeight = height / 3
    for item in range(count):
        # 鼠标悬停事件
        ActionChains(browser).move_to_element_with_offset(series,
                                                          xoffset=itemWidth * item,
                                                          yoffset=itemHeight).perform()
        tip = svg.find_element_by_css_selector("g[class='highcharts-tooltip']")
        tip = tip.find_element_by_tag_name("text")
        time.sleep(1)
        # "2019年01月10日: 0次"
        targetText = tip.text;
        # print(targetText)
        if (len(targetText) > 0):
            _date = targetText[:targetText.find("日")]
            _timeStr = targetText[targetText.find(":") + 2:len(targetText) - 1]
            result.append((formateDate(_date), _timeStr))
    print("xiaomi",result)
    # browser.quit()
    return result


def formateDate(date):
    """
    2019年01月10日
    :return:  2018-12-30
    """
    _dateStr = date.replace("年", "-").replace("月", "-").replace("日", "")
    _date = datetime.strptime(_dateStr, "%Y-%M-%d");
    _dateTuple = _date.timetuple();
    return str(_dateTuple.tm_year) + "-" + str(_dateTuple.tm_mon) + "-" + str(_dateTuple.tm_mday)

# print(formateDate("2019年01月10日"))
# loadData()
